<template>
    <div class="order-management">
      <div class="filter-container">
        <el-input
          v-model="queryParams.user_id"
          placeholder="请输入用户ID"
          clearable
          class="filter-item"
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
  
      <!-- 订单列表 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        stripe
        style="width: 100%; margin-top: 15px"
      >
        <el-table-column prop="order_id" label="订单号" width="180" />
        <el-table-column prop="user_name" label="用户名" width="120" />
        <el-table-column prop="goods_name" label="商品名称" width="180" />
        <el-table-column prop="create_time" label="下单时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_status_text" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getOrderStatusTag(scope.row.order_status)">
              {{ scope.row.order_status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="should_price" label="应付金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.should_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="real_price" label="实付金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.real_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="use_coupon" label="使用优惠券" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.use_coupon === 1 ? 'success' : 'info'">
              {{ scope.row.use_coupon === 1 ? '已使用' : '未使用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logistics_number" label="物流单号" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.order_status === 0"
              size="small"
              type="warning"
              @click="handleChangeStatus(scope.row, 5)"
            >
              取消订单
            </el-button>
            <el-button
              v-if="scope.row.order_status === 1"
              size="small"
              type="primary"
              @click="handleDelivery(scope.row)"
            >
              发货
            </el-button>
            <el-button
              v-if="scope.row.order_status === 2"
              size="small"
              type="success"
              @click="handleChangeStatus(scope.row, 4)"
            >
              完成订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 发货对话框 -->
      <el-dialog v-model="deliveryDialogVisible" title="填写物流信息" width="500px">
        <el-form :model="deliveryForm" label-width="100px">
          <el-form-item label="订单号">
            <el-input v-model="deliveryForm.order_id" disabled />
          </el-form-item>
          <el-form-item label="物流单号" required>
            <el-input v-model="deliveryForm.logistics_number" placeholder="请输入物流单号" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deliveryDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitDelivery" :loading="submitLoading">
              确认发货
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import axios from "../../public/request"
  
  // 列表加载状态
  const loading = ref(false)
  const submitLoading = ref(false)
  
  // 查询参数
  const queryParams = reactive({
    page: 1,
    size: 10,
    user_id: ""
  })
  
  // 订单列表数据
  const orderList = ref([])
  const total = ref(0)
  
  // 发货对话框相关数据
  const deliveryDialogVisible = ref(false)
  const deliveryForm = reactive({
    order_id: '',
    logistics_number: ''
  })
  
  // 页面加载时获取订单列表
  onMounted(() => {
    getOrderList()
  })
  
  // 获取订单列表
  const getOrderList = async () => {
    loading.value = true
    try {
      const response = await axios.get('/order_manage/orders', {
        params: queryParams
      })
      if (response.data.code === 200) {
        orderList.value = response.data.data.list
        total.value = response.data.data.total
      } else {
        ElMessage.error(response.data.message || '获取订单列表失败')
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      ElMessage.error('获取订单列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 查询按钮处理
  const handleQuery = () => {
    queryParams.page = 1
    getOrderList()
  }
  
  // 重置查询条件
  const resetQuery = () => {
    queryParams.user_id = ''
    handleQuery()
  }
  
  // 处理每页数量变化
  const handleSizeChange = (val) => {
    queryParams.size = val
    getOrderList()
  }
  
  // 处理页码变化
  const handleCurrentChange = (val) => {
    queryParams.page = val
    getOrderList()
  }
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
  }
  
  // 根据订单状态获取标签类型
  const getOrderStatusTag = (status) => {
    const statusMap = {
      0: 'warning',  // 待付款
      1: 'primary',  // 待发货
      2: 'success',  // 待收货
      3: 'danger',   // 售后中
      4: 'info',     // 已完成
      5: 'info'      // 已取消
    }
    return statusMap[status] || 'info'
  }
  
  // 处理订单状态变更
  const handleChangeStatus = (row, status) => {
    const statusTextMap = {
      0: '待付款',
      1: '待发货',
      2: '待收货',
      3: '售后中',
      4: '已完成',
      5: '已取消'
    }
    
    ElMessageBox.confirm(
      `确定要将订单状态从"${row.order_status_text}"更改为"${statusTextMap[status]}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        try {
          const response = await axios.put('/order_manage/orders/status', {
            order_id: row.order_id,
            order_status: status
          })
          
          if (response.data.code === 200) {
            ElMessage.success('订单状态更新成功')
            getOrderList()
          } else {
            ElMessage.error(response.data.message || '订单状态更新失败')
          }
        } catch (error) {
          console.error('订单状态更新失败:', error)
          ElMessage.error('订单状态更新失败')
        }
      })
      .catch(() => {
        // 用户取消操作
      })
  }
  
  // 处理发货操作
  const handleDelivery = (row) => {
    deliveryForm.order_id = row.order_id
    deliveryForm.logistics_number = ''
    deliveryDialogVisible.value = true
  }
  
  // 提交发货信息
  const submitDelivery = async () => {
    if (!deliveryForm.logistics_number) {
      ElMessage.warning('请输入物流单号')
      return
    }
    
    submitLoading.value = true
    try {
      const response = await axios.put('/order_manage/orders/status', {
        order_id: deliveryForm.order_id,
        order_status: 2, // 将状态改为待收货
        logistics_number: deliveryForm.logistics_number
      })
      
      if (response.data.code === 200) {
        ElMessage.success('发货成功')
        deliveryDialogVisible.value = false
        getOrderList()
      } else {
        ElMessage.error(response.data.message || '发货失败')
      }
    } catch (error) {
      console.error('发货失败:', error)
      ElMessage.error('发货失败')
    } finally {
      submitLoading.value = false
    }
  }
  </script>
  
  <style scoped>
  .order-management {
    padding: 20px;
  }
  
  .filter-container {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .filter-item {
    margin-right: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  </style>